package cn.edu.pzhu.javaweb.controller;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.edu.pzhu.javaweb.pojo.Result;
import cn.edu.pzhu.javaweb.pojo.User;
import cn.edu.pzhu.javaweb.pojo.Userinfo;
import cn.edu.pzhu.javaweb.service.UserService;
import cn.edu.pzhu.javaweb.service.imp.UserServiceImp;

/**
 * Servlet implementation class InitUserServlet
 */
@WebServlet("/init")
public class InitUserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    
    private UserService userService = new UserServiceImp();
    
    /**
     * @see HttpServlet#HttpServlet()
     */
    public InitUserServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		User user = new User("zhangsan","111",1);
		Userinfo userinfo  = new Userinfo("zhangsan","pzhlan@qq.com",1,"[\"法律规定\", \"管理办法\", \"决定条例\"]");
		
		// 调用UserService的regist方法将用户信息保存到数据库
		Result<String> result = userService.regist(user, userinfo);
		
		if (result.getCode() == 0) {
		    // 注册成功
		    response.getWriter().print("<script>alert('测试用户初始化成功！\\n用户名：zhangsan\\n密码：111');location.href='login.jsp';</script>");
		} else {
		    // 注册失败
		    String errorMsg = result.getMsg() != null ? result.getMsg() : "用户初始化失败";
		    response.getWriter().print("<script>alert('" + errorMsg + "');location.href='login.jsp';</script>");
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
